package cn.yangliu.oauth2.service.impl;

import cn.yangliu.oauth2.entity.Oauth2Client;
import cn.yangliu.oauth2.mapper.Oauth2ClientMapper;
import cn.yangliu.oauth2.service.Oauth2ClientService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Primary;
import org.springframework.security.oauth2.provider.ClientAlreadyExistsException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 杨柳
 * @contact 
 * @date 2019-03-26 01:20
 */
@Service
@Slf4j
@Transactional(rollbackFor = Throwable.class)
@Primary //要设置primary 否则无限递归
public class Oauth2ClientServiceImpl extends ServiceImpl<Oauth2ClientMapper,Oauth2Client> implements Oauth2ClientService {


    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        QueryWrapper<Oauth2Client> wrapper = new QueryWrapper<Oauth2Client>().eq("client_id",clientId);
        return baseMapper.selectOne(wrapper);
    }

    @Override
    public void addClientDetails(ClientDetails clientDetails) throws ClientAlreadyExistsException {
        baseMapper.insert((Oauth2Client)clientDetails);
    }

    @Override
    public void updateClientDetails(ClientDetails clientDetails) throws NoSuchClientException {
        Wrapper<Oauth2Client> wrapper = new UpdateWrapper<>((Oauth2Client)clientDetails);
        baseMapper.update((Oauth2Client)clientDetails,wrapper);
    }

    @Override
    public void updateClientSecret(String clientId, String secret) throws NoSuchClientException {
        UpdateWrapper<Oauth2Client> wrapper = Wrappers.update();
        wrapper.set(true, "client_id", clientId);
        Oauth2Client oauth2Client = new Oauth2Client(clientId).setClientSecret(secret);
        baseMapper.update(oauth2Client,wrapper);
    }

    @Override
    public void removeClientDetails(String clientId) throws NoSuchClientException {
        UpdateWrapper<Oauth2Client> wrapper = Wrappers.update();
        wrapper.set(true, "client_id", clientId);
        baseMapper.delete(wrapper);
    }

    @Override
    public List<ClientDetails> listClientDetails() {
        Wrapper<Oauth2Client> empty = Wrappers.emptyWrapper();
        List<Oauth2Client> oauth2Clients = baseMapper.selectList(empty);
        return new ArrayList<>(oauth2Clients);
    }
}
